package com.example.repair.activity;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.MapsInitializer;
import com.example.repair.R;
import com.example.repair.activity.order.AllorderActivity;
import com.example.repair.activity.order.ChangeActivity;
import com.example.repair.base.BaseActivity;
import com.example.repair.base.Presenter.PressenterImpl;
import com.example.repair.base.netWork.Constant;
import com.example.repair.base.netWork.LoginContract;
import com.example.repair.entity.Bean;
import com.example.repair.entity.GetUserInfo;
import com.example.repair.util.SpUtils;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements LoginContract.IView {
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.id)
    TextView id;
    @BindView(R.id.all_num)
    TextView all_num;
    @BindView(R.id.finish_num)
    TextView finish_num;
    @BindView(R.id.no_num)
    TextView no_num;

    private AMapLocation aMapLocations;

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

            if (aMapLocation.getErrorCode() == 0) {
                aMapLocations = aMapLocation;

                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("lng",aMapLocation.getLongitude()+"");
                map.put("lat",aMapLocation.getLatitude()+"");
                pressenter.sendMessage(MainActivity.this,Constant.user_location,map, Bean.class);

                SpUtils.saveString(MainActivity.this,"lng",aMapLocation.getLongitude()+"");
                SpUtils.saveString(MainActivity.this,"lat",aMapLocation.getLatitude()+"");
                SpUtils.saveString(MainActivity.this,"location",aMapLocation.getProvince()+aMapLocation.getCity()+aMapLocation.getDistrict());



//可在其中解析amapLocation获取相应内容。
            } else {
                Toast.makeText(MainActivity.this, "失败：ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo(), Toast.LENGTH_SHORT).show();
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }


        }
    };

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private PressenterImpl pressenter;
    private String uid;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        uid = SpUtils.getString(this, "uid");
        MapsInitializer.updatePrivacyShow(MainActivity.this,true,true);
        MapsInitializer.updatePrivacyAgree(MainActivity.this,true);

        getWindow().setStatusBarColor(getResources().getColor(R.color.main));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//                            getWindow().getDecorView().setSystemUiVisibility(View.);

            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);

        }

        setLocation();

    }

    private void setLocation() {
//初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(3600000);
//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(false);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();


    }


    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid", uid);

        pressenter.sendMessage(this, Constant.get_userinfo, map, GetUserInfo.class);




    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfo) {
            GetUserInfo getUserInfo = (GetUserInfo) data;
            if (getUserInfo.getCode()==1){
                image.setImageURI(Constant.PATH+getUserInfo.getData().getHeadsmall());
                nick.setText(getUserInfo.getData().getUser_nickname());
                id.setText("ID："+getUserInfo.getData().getUid()+"");
                all_num.setText(getUserInfo.getData().getAllOrderCount()+"");
                finish_num.setText(getUserInfo.getData().getOverOrderCount()+"");
                no_num.setText(getUserInfo.getData().getWeiOrderCount()+"");
            }else {
                Toast.makeText(this, getUserInfo.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void fail(String error) {

    }

    @OnClick({R.id.setting, R.id.nofinish, R.id.allorder, R.id.fenpei, R.id.repairing, R.id.payed, R.id.finished, R.id.failed, R.id.allOrder, R.id.finish, R.id.nofinish})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.setting:
                intent=new Intent(MainActivity.this,SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.allOrder:
            case R.id.allorder:
                intent=new Intent(MainActivity.this, AllorderActivity.class);
                intent.putExtra("type","1");
                startActivity(intent);
                break;
            case R.id.finished:
            case R.id.finish:
                intent=new Intent(MainActivity.this, AllorderActivity.class);
                intent.putExtra("type","5");
                startActivity(intent);
                break;
            case R.id.fenpei:
                intent=new Intent(MainActivity.this, AllorderActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
                break;
            case R.id.repairing:
                intent=new Intent(MainActivity.this, AllorderActivity.class);
                intent.putExtra("type","3");
                startActivity(intent);
                break;
            case R.id.payed:
                intent=new Intent(MainActivity.this, AllorderActivity.class);
                intent.putExtra("type","4");
                startActivity(intent);
                break;
            case R.id.failed:
            case R.id.nofinish:
                intent=new Intent(MainActivity.this, AllorderActivity.class);
                intent.putExtra("type","-1");
                startActivity(intent);
                break;
        }
    }

    /**
     * 防止误触退出
     */
    private long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
